// routes/attachmentRoutes.js
const express = require('express');
const router = express.Router();
const attachmentModel = require('../controllers/attachmentControll');

router.get('/blog/:blogId', async (req, res) => {
  try {
    const attachments = await attachmentModel.getAttachmentsByBlogId(req.params.blogId);
    res.json(attachments);
  } catch (error) {
    res.status(500).json({ message: error.message });
  }
});


router.post('/upload', async (req, res) => {
  try {
    const { blog_id, file_name, file_path } = req.body;
    const attachmentId = await attachmentModel.createAttachment(blog_id, file_name, file_path);
    res.status(201).json({ attachmentId });
  } catch (error) {
    res.status(500).json({ message: error.message });
  }
});

// 文件下载路由
router.get('/download/:filename', (req, res) => {
  const filename = req.params.filename;
  const filePath = path.join(__dirname, '..', 'public', 'loads', filename);

  if (fs.existsSync(filePath)) {
    res.download(filePath);
  } else {
    res.status(404).json({ message: 'File not found' });
  }
});
router.delete('/:id', async (req, res) => {
  try {
    await attachmentModel.deleteAttachment(req.params.id);
    res.json({ message: 'Attachment deleted successfully' });
  } catch (error) {
    res.status(500).json({ message: error.message });
  }
});

module.exports = router;
